//
//  SINetworkTools.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/2.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit
import AFNetworking

enum SIHTTPMethod {
    case GET
    case POST
}

class SINetworkTools: AFHTTPSessionManager {
    
    static let shared: SINetworkTools = {
        
        let instance = SINetworkTools()
        
        //afn支持的返回值类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    lazy var userAccount = SIUserAccount() //"2.00rZRZhCBBZ43D573791b4ackvyyuD"
    var uid: String? = "2476057163"
    
    var userLogon: Bool {
        return userAccount.access_token != nil
    }
    
    func tokenRequests(method: SIHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?,name: String? = nil, data: Data? = nil, completion: (json: AnyObject?, isSuccess: Bool) -> ()) {
        
        guard let token = userAccount.access_token else {
            
            //FIXME: 发送通知,提示用户登录
            print("没有 token! 需要登录")
            ///如果token为nil.就发送通知
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: userNeedLoginSinaNotification), object: nil)
            
            completion(json: nil, isSuccess: false)
            
            return
        }
        
        var parameters = parameters
        
        if parameters == nil {
            
            parameters = [String: AnyObject]()
        }
        
        parameters?["access_token"] = token
        
        if let name = name, data = data {
            
            upload(URLString: URLString, parameters: parameters, name: name, data: data, completion: completion)
        } else {
            
            request(method: method, URLString: URLString, parameters: parameters, completion: completion)
        }
        
    }
    
    // MARK: 微博上传文件方法 封装AFN的上传文件方法
    ///上传文件 必须是post方法 
    func upload(URLString: String, parameters: [String: AnyObject]?, name: String, data: Data, completion:(json: AnyObject?, isSuccess: Bool) -> ()) {
        
        post(URLString, parameters: parameters, constructingBodyWith: { (formData) in
            // FIXME: - 创建formData
            formData.appendPart(withFileData: data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
            
            }, progress: nil, success: { (_, json) in
                
                completion(json: json, isSuccess: true)
                
            }) { (task, error) in
                
                if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                    
                    print("Token过期了")
                    
                    //FIXME: 发送通知, 提示用户再次登录
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: userNeedLoginSinaNotification), object: "invalid token")
                    
                }
                
                print("网络请求错误 \(error)")
                
                completion(json: nil, isSuccess: false)
                
        }
        
    }
    
    
    
    //MARK: - 隔离AFN的GET 和 POST 
    func request(method: SIHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?, completion: (json: AnyObject?, isSuccess: Bool) -> ()) {
        
        
        let success = {(task: URLSessionDataTask, json: AnyObject?) -> () in
            
            completion(json: json, isSuccess: true)
            
        }
        
        let failure = {(task: URLSessionDataTask?, error: NSError) -> () in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                
                print("Token过期了")
                
                //FIXME: 发送通知, 提示用户再次登录
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: userNeedLoginSinaNotification), object: "invalid token")
                
            }
            
            print("网络请求错误 \(error)")
            
            completion(json: nil, isSuccess: false)
            
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
        
    }
    

}
